package com.boyiis.sell.controller;

import com.boyiis.sell.model.entity.Product;
import com.boyiis.sell.model.entity.ProductCategory;
import com.boyiis.sell.service.ProductCategoryService;
import com.boyiis.sell.service.ProductService;
import com.boyiis.sell.model.vo.ProductVO;
import com.boyiis.sell.model.vo.CategoryVO;
import com.boyiis.sell.model.vo.Result;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/buyer/product")
public class BuyerProductController {

    @Autowired
    private ProductService productService;

    @Autowired
    private ProductCategoryService productCategoryService;

    @GetMapping("/list")
    @Cacheable(cacheNames = "product", key = "123")
    public Result list() {
        Result<List<CategoryVO>> result = new Result();
        List<Product> productList = productService.findUpAll();

        List<Integer> categoryTypeList = productList.stream()
                .map(e -> e.getCategoryType())
                .collect(Collectors.toList());
        List<ProductCategory> productCategoryList = productCategoryService.findByCategoryTypeIn(categoryTypeList);

        List<CategoryVO> categoryVOList = new ArrayList<CategoryVO>();
        for (ProductCategory productCategory : productCategoryList) {
            CategoryVO categoryVO = new CategoryVO();
            categoryVO.setCategoryType(productCategory.getCategoryType());
            categoryVO.setCategoryName(productCategory.getCategoryName());

            List<ProductVO> productVOList = new ArrayList<ProductVO>();
            for(Product product : productList){
                if(product.getCategoryType().equals(productCategory.getCategoryType())){
                    ProductVO productVO = new ProductVO();
                    BeanUtils.copyProperties(product, productVO);
                    productVOList.add(productVO);
                }
            }
            categoryVO.setProductVOList(productVOList);
            categoryVOList.add(categoryVO);
        }

        result.setCode(0);
        result.setMsg("成功");

        result.setData(categoryVOList);
        return result;
    }
}
